package com.i8office.android.zhihuixinwu.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.cyan.tools.util.RxBus;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.i8office.android.zhihuixinwu.R;
import com.i8office.android.zhihuixinwu.ui.DetailActivity;
import com.i8office.android.zhihuixinwu.ui.dep.DetailDepActivity;
import com.socks.library.KLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.Executors;

import app.Main;
import application.AppApplication;
import application.HttpUrlConstant;
import bean.DeptConfig;
import bean.Result;
import bean.WorkFlow;
import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import utils.NotificationUtils;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "JIGUANG-Example";
    private Context context;

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            this.context = context;
            final Bundle bundle = intent.getExtras();
            KLog.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                KLog.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
                //send the Registration Id to your server...

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                KLog.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
//				processCustomMessage(context, bundle);
//                String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//                NotificationUtils utils = new NotificationUtils(context);
//                utils.sendNotification(context.getString(R.string.app_name),message);


            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                KLog.d(TAG, "[MyReceiver] 接收到推送下来的通知");
                int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
                KLog.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
                try {
                    String str = bundle.getString(JPushInterface.EXTRA_EXTRA);
                    if (!TextUtils.isEmpty(str)) {
                        JSONObject jsonObject = new JSONObject(str);
                        String type = jsonObject.optString("type");
                        if (type.equals("Workflow")) {
                            RxBus.get().post("submitSuccess", "");
                        }
                    }
                } catch (Exception e) {
                    KLog.d(TAG, "[MyReceiver] j接收消息出错了: " + notifactionId);
                }

            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                KLog.d(TAG, "[MyReceiver] 用户点击打开了通知");
                Executors.newCachedThreadPool().execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String str = bundle.getString(JPushInterface.EXTRA_EXTRA);
                            JSONObject jsonObject = new JSONObject(str);
                            String type = jsonObject.optString("type");
                            if (type.equals("Workflow")) {
                                String mid = jsonObject.optJSONObject("content").optString("mid");
                                checkWorkFlowType(mid);
                            }
                        } catch (Exception e) {

                        }
                    }
                });

            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                KLog.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                KLog.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
            } else {
                KLog.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e) {

        }

    }

    private void checkWorkFlowType(final String mid) {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("mid", mid)
                .build();
        String urlF = HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.isDeptWorkflow) + "?__session__=" + AppApplication.getSession();
        KLog.e("urlF:" + urlF);
        Request request = new Request.Builder()
                .url(urlF)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String result = response.body().string();
                    KLog.e("result:" + result);
                    final Result<DeptConfig> data = new Gson().fromJson(result, new TypeToken<Result<DeptConfig>>() {
                    }.getType());
                    HandlerUtil.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            if (context != null) {
                                if (data.getData().isDeptWorkflow) {
                                    WorkFlow workFlow = new WorkFlow();
                                    workFlow.setMessageId(mid);
                                    context.startActivity(new Intent(context, Main.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                                    context.startActivity(new Intent(context, DetailDepActivity.class)
                                            .putExtra("workFlow", workFlow)
                                            .putExtra("from", "main")
                                            .putExtra("isNotify", true).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                                } else {
                                    WorkFlow workFlow = new WorkFlow();
                                    workFlow.setMessageId(mid);
                                    context.startActivity(new Intent(context, Main.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                                    context.startActivity(new Intent(context, DetailActivity.class)
                                            .putExtra("workFlow", workFlow)
                                            .putExtra("from", "main")
                                            .putExtra("isNotify", true).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));

                                }
                            }
                        }
                    });
                } catch (Exception e) {
                    KLog.e("出错了" + e.toString());
                }
            }
        });
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    KLog.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    KLog.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.get(key));
            }
        }
        return sb.toString();
    }

//	//send msg to MainActivity
//	private void processCustomMessage(Context context, Bundle bundle) {
//		if (MainActivity.isForeground) {
//			String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//			Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
//			msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
//			if (!ExampleUtil.isEmpty(extras)) {
//				try {
//					JSONObject extraJson = new JSONObject(extras);
//					if (extraJson.length() > 0) {
//						msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
//					}
//				} catch (JSONException e) {
//
//				}
//
//			}
//			LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
//		}
//	}
}
